package cn.lblbc.webbrowser

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import cn.lblbc.webbrowser.utils.BackgroundImageManager

class HomeFragment : Fragment() {
    private lateinit var doubaoShortcut: LinearLayout
    private lateinit var deepseekShortcut: LinearLayout
    private lateinit var wandoujiaShortcut: LinearLayout
    private lateinit var baiduMobileShortcut: LinearLayout
    private lateinit var bilibiliShortcut: LinearLayout
    private lateinit var douyinShortcut: LinearLayout
    private lateinit var xiguaShortcut: LinearLayout
    private lateinit var jinritoutiaoShortcut: LinearLayout
    
    private lateinit var backgroundImageManager: BackgroundImageManager
    
    // 广播接收器，用于监听背景图片更改
    private val backgroundChangeReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == "BACKGROUND_IMAGE_CHANGED") {
                android.util.Log.d("HomeFragment", "Received background change broadcast")
                applyBackgroundImage()
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_home, container, false)
        
        try {
            backgroundImageManager = BackgroundImageManager(requireContext())
            initializeViews(view)
            setupClickListeners()
            applyBackgroundImage()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        
        return view
    }
    
    private fun initializeViews(view: View) {
        // 不再需要 backgroundImageView，背景直接设置到 MainActivity 的根布局上
        doubaoShortcut = view.findViewById(R.id.doubaoShortcut) ?: throw IllegalStateException("doubaoShortcut not found in layout")
        deepseekShortcut = view.findViewById(R.id.deepseekShortcut) ?: throw IllegalStateException("deepseekShortcut not found in layout")
        wandoujiaShortcut = view.findViewById(R.id.wandoujiaShortcut) ?: throw IllegalStateException("wandoujiaShortcut not found in layout")
        baiduMobileShortcut = view.findViewById(R.id.baiduMobileShortcut) ?: throw IllegalStateException("baiduMobileShortcut not found in layout")
        bilibiliShortcut = view.findViewById(R.id.bilibiliShortcut) ?: throw IllegalStateException("bilibiliShortcut not found in layout")
        douyinShortcut = view.findViewById(R.id.douyinShortcut) ?: throw IllegalStateException("douyinShortcut not found in layout")
        xiguaShortcut = view.findViewById(R.id.xiguaShortcut) ?: throw IllegalStateException("xiguaShortcut not found in layout")
        jinritoutiaoShortcut = view.findViewById(R.id.jinritoutiaoShortcut) ?: throw IllegalStateException("jinritoutiaoShortcut not found in layout")
    }

    private fun setupClickListeners() {
        try {
            // 使用安全调用运算符，确保所有控件都已初始化
            doubaoShortcut?.setOnClickListener {
                hideKeyboard()
                (activity as? MainActivity)?.loadUrl("https://www.quark.cn/")
            }
            
            deepseekShortcut?.setOnClickListener {
                hideKeyboard()
                (activity as? MainActivity)?.loadUrl("https://www.baidu.com/")
            }
            
            wandoujiaShortcut?.setOnClickListener {
                hideKeyboard()
                (activity as? MainActivity)?.loadUrl("https://www.so.com/")
            }
            
            baiduMobileShortcut?.setOnClickListener {
                hideKeyboard()
                (activity as? MainActivity)?.loadUrl("https://www.sogou.com/")
            }
            
            bilibiliShortcut?.setOnClickListener {
                hideKeyboard()
                (activity as? MainActivity)?.loadUrl("https://www.douyin.com/")
            }
            
            douyinShortcut?.setOnClickListener {
                hideKeyboard()
                (activity as? MainActivity)?.loadUrl("https://v.qq.com/")
            }
            
            xiguaShortcut?.setOnClickListener {
                hideKeyboard()
                (activity as? MainActivity)?.loadUrl("https://www.iqiyi.com/")
            }
            
            jinritoutiaoShortcut?.setOnClickListener {
                hideKeyboard()
                (activity as? MainActivity)?.loadUrl("https://www.youku.com/")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    private fun hideKeyboard() {
        try {
            val activity = activity ?: return
            val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            val view = activity.currentFocus ?: View(activity)
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        } catch (e: Exception) {
            // 处理可能的异常
        }
    }
    
    override fun onResume() {
        super.onResume()
        // 在页面恢复时刷新背景图片，以便在设置更改后能及时更新
        try {
            applyBackgroundImage()
            // 注册广播接收器
            LocalBroadcastManager.getInstance(requireContext())
                .registerReceiver(backgroundChangeReceiver, IntentFilter("BACKGROUND_IMAGE_CHANGED"))
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    override fun onPause() {
        super.onPause()
        try {
            // 取消注册广播接收器
            LocalBroadcastManager.getInstance(requireContext())
                .unregisterReceiver(backgroundChangeReceiver)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    /**
     * 应用背景图片设置
     */
    private fun applyBackgroundImage() {
        try {
            android.util.Log.d("HomeFragment", "applyBackgroundImage() called")
            android.util.Log.d("HomeFragment", "backgroundImageManager initialized: ${::backgroundImageManager.isInitialized}")
            
            if (::backgroundImageManager.isInitialized) {
                val currentBg = backgroundImageManager.getCurrentBackgroundImage()
                android.util.Log.d("HomeFragment", "Current background setting: $currentBg")
                
                // 获取 MainActivity 中的背景 ImageView
                val backgroundImageView = (activity as? MainActivity)?.findViewById<ImageView>(R.id.backgroundImageView)
                
                if (backgroundImageView != null) {
                    android.util.Log.d("HomeFragment", "Applying background to MainActivity's backgroundImageView")
                    backgroundImageManager.applyBackgroundToImageView(backgroundImageView)
                    android.util.Log.d("HomeFragment", "Background application completed")
                } else {
                    android.util.Log.e("HomeFragment", "MainActivity backgroundImageView not found")
                }
            } else {
                android.util.Log.e("HomeFragment", "Cannot apply background - backgroundImageManager not initialized")
            }
        } catch (e: Exception) {
            android.util.Log.e("HomeFragment", "Error applying background image", e)
            e.printStackTrace()
        }
    }
}